package com.juyu.miliao.api.service.whitepacket;

import com.juyu.miliao.api.dao.mysql.*;
import com.juyu.miliao.api.dao.redis.DynamicCommentInfoRedisDao;
import com.juyu.miliao.api.dao.redis.DynamicInfoRedisDao;
import com.juyu.miliao.api.dao.redis.FollowRedisDao;
import com.juyu.miliao.api.dao.redis.usercache.UserCacheVo;
import com.juyu.miliao.api.dao.redis.usercache.UserInfoCache;
import com.juyu.miliao.api.domain.*;
import com.juyu.miliao.api.domain.dto.DynamicInfoDTO;
import com.juyu.miliao.api.domain.dto.DynamicReportInfoDTO;
import com.juyu.miliao.api.domain.dto.WhitePacketDynamicInfoDTO;
import com.juyu.miliao.api.domain.vo.*;
import com.juyu.miliao.api.service.AppKeyService;
import com.juyu.miliao.api.service.DynamicCommentInfoService;
import com.juyu.miliao.api.util.PageUtil;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.util.DateUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 白包动态社区service
 *
 * @author xuanqicheng
 * @create 2019-21-09:47
 */
@Service
public class WhitePacketDynamicInfoService extends BasicWhitePacketService {

    @Autowired
    private WhitePacketDynamicInfoDao whitePacketDynamicInfoDao;

    @Autowired
    private WhitePacketDynamicSourceInfoDao whitePacketDynamicSourceInfoDao;

    @Autowired
    private WhitePacketDynamicLikeInfoDao whitePacketDynamicLikeInfoDao;

    @Autowired
    private WhitePacketDynamicCommentInfoDao whitePacketDynamicCommentInfoDao;

    @Autowired
    private WhitePacketCommentReplyInfoDao whitePacketCommentReplyInfoDao;

    @Autowired
    private FollowRedisDao followRedisDao;

    @Autowired
    private UserInfoCache userInfoCache;

    @Autowired
    private AppKeyService appKeyService;


    @Transactional(rollbackFor = Exception.class)

    public void addDynamciInfo(WhitePacketDynamicInfoDTO dynamicInfoDTO) {

        WhitePacketDynamicInfo dynamicInfo = new WhitePacketDynamicInfo();

        BeanUtils.copyProperties(dynamicInfoDTO, dynamicInfo);

        whitePacketDynamicInfoDao.addDynamciInfo(dynamicInfo);

        whitePacketDynamicSourceInfoDao.addDynamicSourceInfos(dynamicInfo.getDynamicId(), dynamicInfoDTO);

    }

    public Object clickDynamicLike(Long userId, long dynamicId) {

        WhitePacketDynamicLikeInfo obj = new WhitePacketDynamicLikeInfo();

        obj.setDynamicId(dynamicId);

        obj.setUserId(userId);

        int result = whitePacketDynamicLikeInfoDao.selectDynamicLike(obj);

        if (result > 0) {
            //取消点赞
            JSONObject json = new JSONObject();
            whitePacketDynamicLikeInfoDao.deleteDynamicLikeInfo(obj);
            json.put("type", "remove");
            return json;
        } else {
            //点赞
            JSONObject json = new JSONObject();
            whitePacketDynamicLikeInfoDao.addDynamicLikeInfo(obj);
            json.put("type", "add");
            return json;
        }
    }

    /**
     * 更新动态分享次数
     * @param dynamicId
     */
    public void setShareInfo(Long dynamicId) {

        WhitePacketDynamicShareInfo dynamicShareInfo = whitePacketDynamicInfoDao.getDynamicShareByDynamicId(dynamicId);
        if (dynamicShareInfo == null) {
            whitePacketDynamicInfoDao.addDynamicShare(dynamicId);

        } else {
            whitePacketDynamicInfoDao.updateShareNumber(dynamicId);
        }

    }

    public void deleteDynamicInfo(long dynamicId) {
        whitePacketDynamicInfoDao.deleteDynamicInfo(dynamicId);
    }

    /**
     * 查看动态列表
     * @param userId
     * @param appKey
     * @param page
     * @param pageSize
     * @return
     */
    public List<WhitePacketDynamicInfoVo> getDynamicInfoList(long userId,String appKey,Integer page, Integer pageSize) {

        int startNum = PageUtil.getOffset(page, pageSize);

        List<WhitePacketDynamicInfoVo> list = whitePacketDynamicInfoDao.getDynamicInfoList(startNum, pageSize,appKey);

        setDynamicInfo(userId,list);

        return list;
    }


    /**
     * 根据用户id，查询信息
     * @param appKey
     * @param reqUserId 访问用户id
     * @param userId    动态用户id
     * @param page
     * @param pageSize
     * @return
     */
    public List<WhitePacketDynamicInfoVo> getDynamicInfoListByUserId(String appKey,long reqUserId, Long userId, Integer page, Integer pageSize) {

        int startNum = PageUtil.getOffset(page, pageSize);

        List<WhitePacketDynamicInfoVo> list = whitePacketDynamicInfoDao.selectDynamicListUserIdPage(appKey,userId,
                startNum, pageSize);

        setDynamicInfo(reqUserId, list);

        return list;
    }


    /**
     * 根据动态id 查询内容
     * @param dynamicId
     * @param userId    当前访问用户的id
     * @return
     */
    public Object getDynamicInfoById(long dynamicId, Long userId) {

        WhitePacketDynamicDetailInfoVo dynamicDetailInfoVo = whitePacketDynamicInfoDao.getDynamicInfoById(dynamicId);

        if (dynamicDetailInfoVo != null) {

            boolean bl = checkDynamicLike(userId,dynamicId);
            if (bl) {
                dynamicDetailInfoVo.setIsLike(1);
            }

            String showTime = DateUtil.getShowTime(dynamicDetailInfoVo.getDynamicCreateTime());

            dynamicDetailInfoVo.setShowTime(showTime);

            int likeNumber = getLikeNumber(dynamicId);

            int shareNumber = getShareNumber(dynamicId);

            int commentSize = getCommentSize(dynamicId);

            List<WhitePacketDynamicSourceInfoVO> sourceInfoVOS = getWhitePacketDynamicSourceInfoVOS(dynamicId);

            UserCacheVo userCacheVo = userInfoCache.getUserCacheInfo(dynamicDetailInfoVo.getUserId());

            dynamicDetailInfoVo.setLikeNumber(likeNumber)
                    .setCommentNumber(commentSize)
                    .setNickName(userCacheVo.getNickName())
                    .setIcon(userCacheVo.getIcon())
                    .setSex(userCacheVo.getSex())
                    .setIsVip(userCacheVo.getIsVip())
                    .setMGrade(userCacheVo.getMGrade())
                    .setVGrade(userCacheVo.getVGrade())
                    .setAge(userCacheVo.getAge())
                    .setIsHost(userCacheVo.getIsHost())
                    .setDynamicSourceUrls(sourceInfoVOS)
                    .setShareNumber(shareNumber);

            Optional<Long> countFollow = followRedisDao.countFollow(userId, dynamicDetailInfoVo.getUserId());

            if (countFollow.isPresent() || userId.equals(dynamicDetailInfoVo.getUserId())) {

                dynamicDetailInfoVo.setIsFollow(1);
            }

            List<WhitePacketDynamicGiftInfo> giftInfos = whitePacketDynamicInfoDao.getDynamicGiftListByDynamicId(dynamicId);

            List<Long> giftUserList = whitePacketDynamicInfoDao.getDynamicGiftUserList(dynamicId);

            if (giftInfos.size() > 0) {
                Map<String, Object> giftMap = new HashMap<>(0);
                giftMap.put("giftNumber", giftInfos.size());
                List<String> iconList = new ArrayList<>();
                List<Long> list;

                if (giftUserList.size() >= 3) {
                    list = giftUserList.subList(0, 3);
                } else {

                    list = giftUserList;
                }
                for (long sendUserId : list) {
                    UserCacheVo userInfo = userInfoCache.getUserCacheInfo(sendUserId);

                    iconList.add(userInfo.getIcon());
                }
                giftMap.put("icons", iconList);

                dynamicDetailInfoVo.setGift(giftMap);
            }

            return dynamicDetailInfoVo;

        } else {
            return new HashMap<>(0);
        }

    }


    /**
     * 设置动态列表信息
     *
     * @param list
     */
    private void setDynamicInfo(long reqUserId, List<WhitePacketDynamicInfoVo> list) {

        for (WhitePacketDynamicInfoVo obj : list) {

            boolean bl = checkDynamicLike(reqUserId, obj.getDynamicId());

            if (bl) {
                obj.setIsLike(1);
            }

            int shareNumber = getShareNumber(obj.getDynamicId());


            obj.setShowTime(DateUtil.getShowTime(obj.getDynamicCreateTime()));

            //获取点赞数
            int likeNumber = getLikeNumber(obj.getDynamicId());

            int commentSize = getCommentSize(obj.getDynamicId());

            List<WhitePacketDynamicSourceInfoVO> sourceInfoVOS = getWhitePacketDynamicSourceInfoVOS(obj.getDynamicId());

            UserCacheVo userCacheVo = userInfoCache.getUserCacheInfo(obj.getUserId());
            obj.setNickName(userCacheVo.getNickName())
                    .setIcon(userCacheVo.getIcon())
                    .setSex(userCacheVo.getSex())
                    .setIsVip(userCacheVo.getIsVip())
                    .setMGrade(userCacheVo.getMGrade())
                    .setVGrade(userCacheVo.getVGrade())
                    .setAge(userCacheVo.getAge())
                    .setIsHost(userCacheVo.getIsHost())
                    .setCommentNumber(commentSize)
                    .setLikeNumber(likeNumber)
                    .setShareNumber(shareNumber)
                    .setDynamicSourceUrls(sourceInfoVOS);

            List<WhitePacketDynamicCommentInfo> commentInfoList = whitePacketDynamicCommentInfoDao
                    .getDynamicCommentPageByDynamicId(obj.getDynamicId(), 0, 2);

            if (commentInfoList.size() > 0) {

                WhitePacketDynamicCommentInfoVo dynamicCommentInfoVo = new WhitePacketDynamicCommentInfoVo();

                //获取评论信息
                WhitePacketDynamicCommentInfo commentInfo = commentInfoList.get(0);

                setDynamicCommentInfoVo(dynamicCommentInfoVo, commentInfo);

                List<WhitePacketCommentReplyInfo> commentReplyInfoList =whitePacketCommentReplyInfoDao
                        .getCommentReplyInfoByCommentId(commentInfo.getId());
                if (commentReplyInfoList.size() > 0) {

                    WhitePacketCommentReplyInfo commentReplyInfo = commentReplyInfoList.get(0);

                    Map<String, Object> map = setCommentReplyInfo(commentReplyInfoList.size(),
                            commentReplyInfo);

                    dynamicCommentInfoVo.setReplyInfo(map);

                }
                obj.setComment(dynamicCommentInfoVo);


            } else {
                obj.setComment(new HashMap<>(1));
            }

        }
    }

    private List<WhitePacketDynamicSourceInfoVO> getWhitePacketDynamicSourceInfoVOS(long dynamicId) {
        return whitePacketDynamicSourceInfoDao.selectDynamicSourcesByDynamicId(dynamicId);
    }

    private int getCommentSize(long dynamicId) {
        return whitePacketDynamicCommentInfoDao.getDynamicCommentCountByDynamicId(dynamicId);
    }

    private int getLikeNumber(long dynaimcId) {
        return whitePacketDynamicLikeInfoDao.selectDynamicLikeCount(dynaimcId);
    }

    /**
     * 获取分享数
     * @param dynamicId
     * @return
     */
    private int getShareNumber(long dynamicId) {
        WhitePacketDynamicShareInfo dynamicShareInfo = whitePacketDynamicInfoDao.getDynamicShareByDynamicId(dynamicId);

        int shareNumber = 0;

        if(dynamicShareInfo!=null){
            shareNumber = dynamicShareInfo.getShareNum();
        }
        return shareNumber;
    }

    /**
     * 检验是否关注
     * @param reqUserId
     * @param dynamicId
     * @return
     */
    private boolean checkDynamicLike(long reqUserId, long dynamicId) {
        boolean bl = false;

        WhitePacketDynamicLikeInfo like=whitePacketDynamicLikeInfoDao.selectDynamicLikeByDynamicAndUserId(reqUserId, dynamicId);
        if(like!=null){
            bl=true;
        }
        return bl;
    }

    /**
     * 根据id获取动态信息
     * @param dynamicId
     * @return
     */
    public WhitePacketDynamicDetailInfoVo getDynamicInfoByDynamicId(Long dynamicId) {
        WhitePacketDynamicDetailInfoVo dynamicDetailInfoVo = whitePacketDynamicInfoDao.getDynamicInfoById(dynamicId);
        return dynamicDetailInfoVo;
    }

    /**
     * 赠送礼物
     * @param entity
     * @param dynamicId
     */
    public void saveDynamicGiftInfo(GiftSpend entity, Long dynamicId) {

        long userId = Long.parseLong(entity.getOutUserId() + "");

        WhitePacketDynamicGiftInfo dynamicGiftInfo = new WhitePacketDynamicGiftInfo()
                .setDynamicId(dynamicId)
                .setSendUserId(userId)
                .setSendId(entity.getSpendId());

        whitePacketDynamicInfoDao.saveDynamicGiftInfo(dynamicGiftInfo);
    }

    /**
     * 蜜友圈
     * @param appKey
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    public List<WhitePacketDynamicInfoVo> getFollowDynamicInfoListByUserId(String appKey,long userId, Integer page,
                                                                           Integer pageSize) {
        int startNum = PageUtil.getOffset(page, pageSize);

        Set<Long> set = followRedisDao.getFolllowAllByUserId(userId);

        List<Long> followUserList = new ArrayList<>(set);
        if(followUserList.size()>0) {
            List<WhitePacketDynamicInfoVo> list = whitePacketDynamicInfoDao.selectDynamicListFollowPage(appKey, followUserList, startNum, pageSize);

            setDynamicInfo(userId, list);

            return list;
        }else{
            return new ArrayList<>();
        }
    }

    public Map<String, Object> getShareDynamicInfoByDynamicId(Long dynamicId) {
        Map<String, Object> map = new HashMap<>(2);
        WhitePacketDynamicDetailInfoVo obj = whitePacketDynamicInfoDao.getDynamicInfoById(Math.abs(dynamicId));
        if (obj != null) {

            UserCacheVo userCacheVo = userInfoCache.getUserCacheInfo(obj.getUserId());
            map.put("title", userCacheVo.getNickName());
            map.put("content", obj.getDynamicTextContent());

            List<WhitePacketDynamicSourceInfoVO> dynamicSourceList = whitePacketDynamicSourceInfoDao.selectDynamicSourcesByDynamicId(Math.abs(dynamicId));

            if (dynamicSourceList.size() > 0) {
                WhitePacketDynamicSourceInfoVO dynamicSourceInfo = dynamicSourceList.get(0);
                if (obj.getSourceType() == 1) {
                    map.put("icon", dynamicSourceInfo.getDynamicSourceUrl());
                } else if (obj.getSourceType() == 2) {
                    map.put("icon", dynamicSourceInfo.getVideoImgUrl());
                }
            }else{
                map.put("icon","");
            }

            Appkey appkey = appKeyService.getAppKeyByKey("dynamicShareUrl");
            map.put("url",appkey.getValue()+dynamicId);

        }

        return map;
    }

    public WhitePacketDynamicDetailInfoVo getShareTextDynamicInfoByDynamicId(Long dynamicId) {
        WhitePacketDynamicDetailInfoVo obj = whitePacketDynamicInfoDao.getDynamicInfoById(dynamicId);
        if (obj != null) {
            String showTime = DateUtil.getShowTime(obj.getDynamicCreateTime());
            UserCacheVo userCacheVo = userInfoCache.getUserCacheInfo(obj.getUserId());
            obj.setNickName(userCacheVo.getNickName())
                    .setIcon(userCacheVo.getIcon())
                    .setSex(userCacheVo.getSex())
                    .setAge(userCacheVo.getAge())
                    .setIsVip(userCacheVo.getIsVip())
                    .setIsHost(userCacheVo.getIsHost())
                    .setVGrade(userCacheVo.getVGrade())
                    .setMGrade(userCacheVo.getMGrade())
                    .setShowTime(showTime);
            return obj;
        } else {
            throw new ConsumeRuntimeException("动态id不正确");
        }
    }
}
